/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_guestbook.htm
 *
 * Zhiqim Guestbook is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.example.gbook.action;

import org.zhiqim.example.gbook.SessionUser;
import org.zhiqim.example.gbook.dbo.Admin;
import org.zhiqim.httpd.HttpRequest;
import org.zhiqim.httpd.context.extend.GetPostAction;
import org.zhiqim.httpd.util.Sessions;
import org.zhiqim.httpd.validate.ones.IsNotEmpty;
import org.zhiqim.httpd.validate.ones.IsNumericLen;
import org.zhiqim.orm.ORM;

/**
 * 管理员登录
 *
 * @version v1.0.0 @author zouzhigang 2016-9-1 新建与整理
 */
public class AdminLoginAction extends GetPostAction
{
    @Override
    public void validate(HttpRequest request)
    {
        request.addValidate(new IsNotEmpty("adminName", "管理员账号不能为空"));
        request.addValidate(new IsNotEmpty("adminPass", "管理员密码不能为空"));
        request.addValidate(new IsNumericLen("verificationCode", "验证码必须是4位数字", 4, 4));
    }
    
    @Override
    protected void doGet(HttpRequest request) throws Exception
    {//登录页面
    }
    
    @Override
    public void doPost(HttpRequest request) throws Exception
    {//登录处理
        String verificationCode = request.getParameter("verificationCode");
        String vcode = Sessions.getSessionVerificationCode(request);
        if (!verificationCode.equals(vcode))
        {
            request.returnHistory("验证码不正确或已失效，请新输入！");
            return;
        }
        
        String adminName = request.getParameter("adminName");
        String adminPass = request.getParameter("adminPass");
        
        //验证管理员名称和密码是否正确
        Admin admin = ORM.table().item(Admin.class, adminName);
        if(admin == null || !adminPass.equals(admin.getAdminPass()))
        {
            request.returnHistory("账号或密码错误，请重新输入");
            return;
        }
        
        //登录成功，绑定到会话中
        SessionUser sessionUser = new SessionUser();
        sessionUser.setAdmin(admin);
        request.bindSessionUser(sessionUser);
    }
}
